package cn.etynit.service.impl;

import cn.etynit.domain.Employee;
import cn.etynit.domain.User;
import cn.etynit.dto.AccountLoginDto;
import cn.etynit.exception.GlobalExceptionCodeEnum;
import cn.etynit.mms.feign.EmployeeService;
import cn.etynit.mms.feign.UserService;
import cn.etynit.result.JsonResult;
import cn.etynit.service.ILoginService;
import cn.etynit.util.AssertUtil;
import cn.etynit.vo.Logininfo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;


    /**
     * 登录
     * @param accountLoginDto
     * @return
     */
    @Override
    public Map<String,Object> accountLogin(AccountLoginDto accountLoginDto) {
        Integer type = accountLoginDto.getLoginType();
        Logininfo logininfo = new Logininfo();
        if (type.intValue() == AccountLoginDto.EMPLOYEE_LOGIN_ACCOUNT){ // 员工登录
            JsonResult jsonResult = employeeService.accountLogin(accountLoginDto);
            AssertUtil.isTrue(jsonResult.isSuccess(), GlobalExceptionCodeEnum.ERROR);
            Employee employee = JSON.parseObject(JSONObject.toJSONString(jsonResult.getData()), Employee.class);
            BeanUtils.copyProperties(employee,logininfo);
            logininfo.setType(Logininfo.EMPLOYEE_LOGIN);
            return getMap(logininfo);
        } else { // 业主或家庭成员登录
            JsonResult jsonResult = userService.accountLogin(accountLoginDto);
            AssertUtil.isTrue(jsonResult.isSuccess(), GlobalExceptionCodeEnum.ERROR);
            User user = JSON.parseObject(JSONObject.toJSONString(jsonResult.getData()), User.class);
            BeanUtils.copyProperties(user,logininfo);
            logininfo.setType(Logininfo.USER_LOGIN);
            return getMap(logininfo);
        }
    }

    private Map<String,Object> getMap(Logininfo logininfo) {
        // 通过UUID生成token
        String token = UUID.randomUUID().toString();
        // 存入redis，并设置时间30分钟
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        // 将logininfo敏感字段置空
        logininfo.setPassword("");
        logininfo.setPhone("");
        // 返回给前端
        Map<String, Object> hashMap = new HashMap<String, Object>(){{
            put("token",token);
            put("logininfo",logininfo);
        }};
        return hashMap;
    }

}
